package httpService

import (
	"github.com/labstack/echo/v4"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"pm/config"
	"pm/db"
	"pm/model"
	"pm/util"
)

func UploadPackage(c echo.Context)error{

	//获取参数
	version := c.FormValue("version")
	name := c.FormValue("name")
	file := c.FormValue("file")
	desc := c.FormValue("desc")
	if version == "" || name == ""{
		return c.JSON(200, map[string]interface{}{
			"status": 1,
			"msg":"参数错误",
		})
	}


	var exists model.PackageHistory
	err2 := db.NewDb().Where("version = ? AND name = ?", version, name).First(&exists).Error
	if err2 == nil {  // 版本重复
		return c.JSON(200, map[string]interface{}{
			"status": 1,
			"msg":"版本重复",
		})
	}

	//文件转移
	var err1 error
	Data,err := ioutil.ReadFile(file)
	if err != nil{
		return c.JSON(200, map[string]interface{}{
			"status": 1,
			"msg":"文件读取失败",
		})
	}else{
		os.Remove(file)  //删除临时文件
	}
	bakPath := config.ConfigData.PackagesBakPath
	if bakPath == ""{
		fp,_ := util.FileBasePath()
		fp = filepath.Dir(fp)
		bakPath = fp + string(os.PathSeparator) + "packages"
	}
	util.FileCreateFile(bakPath)
	filePath := bakPath+string(os.PathSeparator)+name+"."+version
	err1 = ioutil.WriteFile(filePath, Data, 0644)
	if err1 != nil {
		log.Println("http-UploadPack 备份文件失败-"+err1.Error())
		return c.JSON(200, map[string]interface{}{
			"status": 3,
			"msg":"备份文件失败",
		})
	}
	data := model.PackageHistory{
		Name:       name,
		Version:    version,
		Status:     1,
		Desc: desc,
		FilePath:filePath,
	}
	if err := db.NewDb().Create(&data).Error; err != nil{
		return c.JSON(200, map[string]interface{}{
			"status": 3,
			"msg":"写入数据失败",
		})
	}

	//只备份前三个版本的包
	var packageList []model.PackageHistory
	db.NewDb().Model(&model.PackageHistory{}).
		Where("name = ?", name).
		Order("created_at desc").
		Find(&packageList)
	for k, item := range packageList {
		if k >= 3 && item.Status < 3 {
			err := os.Remove(bakPath + "/" + name + "." + item.Version)
			if err == nil {
				item.Status = 3
				db.NewDb().Model(&model.PackageHistory{}).Where("ID = ?", item.ID).Updates(&item)
			}
		}
	}
	return c.JSON(200, map[string]interface{}{
		"status": 0,
		"msg":"上传成功",
		"data":data.ID,
	})
}
